


const rename = require('gulp-rename')
const del = require('del')  //Node原生的清除方法

const through = require('through2')
const colors = require('ansi-colors')
const log = require('fancy-log')

const postcss = require('gulp-postcss')
const pxtorpx = require('postcss-px2rpx')
const base64 = require('postcss-font-base64')

const htmlmin = require('gulp-htmlmin')
const sass = require('gulp-sass')
const jsonminify = require('gulp-jsonminify')
const combiner = require('stream-combiner2')
const babel = require('gulp-babel')     //支持ES6语法
const uglify = require('gulp-uglify')
const cssnano = require('gulp-cssnano')
const runSequence = require('run-sequence')     //组织任务执行顺序
const sourcemaps = require('gulp-sourcemaps')
const filter = require('gulp-filter')
const jdists = require('gulp-jdists')

const src = './client'
const dist = './dist'
const gulp = require('gulp')
const { series, parallel, watch } = require('gulp');


const isProd = process.env.NODE_ENV === 'production' || false; // 'development'

const handleError = (err) => {
    console.log('\n')
    log(colors.red('Error!'))
    log('fileName: ' + colors.red(err.fileName))
    log('lineNumber: ' + colors.red(err.lineNumber))
    log('message: ' + err.message)
    log('plugin: ' + colors.yellow(err.plugin))
}


/* 清除dist目录 */
gulp.task('clean', done => {
    del.sync(['dist/**/*']);
    done();
});



const json = () => {
    return gulp
        .src(`${src}/**/*.json`)
        .pipe(isProd ? jsonminify() : through.obj())
        .pipe(gulp.dest(dist))
}


gulp.task(json)


const wxml = () => {
    return gulp
        .src(`${src}/**/*.wxml`)
        .pipe(gulp.dest(dist))
}
gulp.task(wxml)


const wxs = () => {
    return gulp
        .src(`${src}/**/*.wxs`)
        .pipe(gulp.dest(dist))
}
gulp.task(wxs)


const scss = (done) => {
    const combined = combiner.obj([
        gulp.src(`${src}/**/*.scss`),
        sass().on('error', sass.logError),
        postcss([pxtorpx(), base64()]),
        isProd
            ? cssnano({
                autoprefixer: false,
                discardComments: { removeAll: true }
            })
            : through.obj(),
        rename((path) => (path.extname = '.wxss')),
        gulp.dest(dist)
    ])

    combined.on('error', handleError)
    done()
}
gulp.task(scss)


const wxss = () => {
    return gulp
        .src(`${src}/**/*.wxss`)

        .pipe(gulp.dest(dist));
};
gulp.task(wxss);






const images = () => {
    return gulp
        .src(`${src}/**/*.images`)
        .pipe(gulp.dest(dist))
}
gulp.task(images)


const js = (done) => {
    const f = filter((file) => !/(mock)/.test(file.path))
    gulp
        .src(`${src}/**/*.js`)
        .pipe(isProd ? f : through.obj())
        .pipe( // // 如果是 prod，则触发 jdists 的 prod trigger  ,否则则为 dev trigger
            isProd
                ? jdists({
                    trigger: 'prod'
                })
                : jdists({
                    trigger: 'dev'
                })
        )
        .pipe(isProd ? through.obj() : sourcemaps.init())
        .pipe(
            babel({
                presets: ['env']
            })
        )
        .pipe(
            isProd
                ? uglify({
                    compress: true
                })
                : through.obj()
        )
        .pipe(isProd ? through.obj() : sourcemaps.write('./'))
        .pipe(gulp.dest(dist))

    done()
}
gulp.task(js)

// cloud-functions 处理方法
const cloudPath = './server/cloud-functions'
const cloud = () => {
    return gulp
        .src(`${cloudPath}/**`)
        .pipe(
            isProd
                ? jdists({
                    trigger: 'prod'
                })
                : jdists({
                    trigger: 'dev'
                })
        )
        .pipe(gulp.dest(`${dist}/cloud-functions`))
}
gulp.task(cloud)




// 监听文件 变化
gulp.task('watch', () => {
    gulp.watch(`${src}/**/*.scss`, scss)
    gulp.watch(`${src}/images/**`, images)
    gulp.watch(`${src}/**/*.wxml`, wxml)
    gulp.watch(`${src}/**/*.wxss`, wxss)
    gulp.watch(`${src}/**/*.js`, js)
    gulp.watch(`${src}/**/*.json`, json)
    gulp.watch(`${src}/**/*.wxs`, wxs)
})


// 开发环境

gulp.task('dev', gulp.series('clean', gulp.parallel('scss', 'json', 'images', 'wxml', 'wxss', 'js', 'wxs', 'cloud'), 'watch'));


// 生产环境
gulp.task('build', gulp.series('clean', 'scss', gulp.parallel('json', 'images', 'wxml', 'wxss', 'js', 'wxs', 'cloud')));

// 云文件 监听
gulp.task('watch:cloud', () => {
    gulp.watch(`${cloudPath}/**`, cloud)
})

// 云文件 - 开发 
gulp.task('cloud:dev', gulp.series('cloud', 'watch:cloud'))
